<template>
  <el-card class="activity-list">
    <el-table :data="activities" border style="width: 100%">
      <el-table-column prop="title" label="活动名称"></el-table-column>
      <el-table-column prop="description" label="内容"></el-table-column>
      <el-table-column prop="startTime" label="开始时间"></el-table-column>
      <el-table-column prop="endTime" label="结束时间"></el-table-column>
      <el-table-column prop="location" label="地点"></el-table-column>

      <!-- 状态列 -->
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-tag :type="statusType(row.status)" size="small">
            {{ formatStatus(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px"
    />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getActivityList } from '@/api/activity'


// 数据定义
const activities = ref([])
const total = ref(0)
const pageSize = ref(5)
const currentPage = ref(1)

// 将数字状态转换为中文文本
const formatStatus = (status) => {
  const statusMap = { '0': '未开始', '1': '进行中', '2': '已结束' }
  return statusMap[status] || status
}

// 获取活动数据
const fetchActivities = async () => {
  try {
    // 使用 getActivityList 接口获取活动列表
    const response = await getActivityList({
      page: Math.ceil(currentPage.value/10),
      size: pageSize.value*10
    });

    const rawData = Array.isArray(response.data) ? response.data : []

    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    const paginatedData = rawData.slice(start, end)


    activities.value = paginatedData
    total.value = rawData.length
  } catch (error) {
    console.error('获取活动数据失败:', error)
    activities.value = []
    total.value = 0
    if(error.code == "ERR_NETWORK") {
      ElMessage.error('获取活动数据失败，请检查网络或稍后再试');
    } else if(error.response.status === 403) {
      ElMessage.error('无权限访问此页面，请重新登录');
    }
  }
}

// 状态标签类型映射
const statusType = (status) => {
  switch (status) {
    case '0':
    case '未开始':
      return 'info'
    case '1':
    case '进行中':
      return 'warning'
    case '2':
    case '已结束':
      return 'success'
    default:
      return 'info' // 默认返回 'info' 以避免无效的 prop
  }
}

// 分页切换
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchActivities()
}

onMounted(() => {
  fetchActivities()
})
</script>

<style scoped>
.activity-list {
  margin: 20px;
}
</style>